<template>
  <div>
    <div>
      <img :class="classType" :src="testImg" alt="">
      <!--      <img :class="classType" :src="localTest" alt="">-->
    </div>
  </div>

</template>

<script>
import axios from "axios";

export default {
  name: "Avatar",
  props: {
    imgUrl: {
      type: String,
      defaults: ""
    },
    classType: {
      type: String,
      defaults: "avatar"
    }
  },
  data() {
    return {
      testImg: "",
      localTest: ""
    }
  },
  watch: {
    imgUrl: {
      handler() {
        this.proavatar();
      },
      deep: true
    }
  },
  mounted() {
    this.proavatar();
  },
  methods: {
    scrollBottom() {
      setTimeout(() => {
        let msg = document.getElementById('message-list')
        msg.scrollTop = msg.scrollHeight
      }, 200)
    },
    proavatar() {
      if (this.imgUrl in this.$store.state.localPicture) {
        this.testImg = this.$store.state.localPicture[this.imgUrl]
      } else {
        axios.get("http://81.70.70.110:4396/file/download/" + this.imgUrl, {
          headers: {
            token: localStorage.getItem("u_token")
          },
          responseType: "blob"
        }).then((res) => {
          let testImg;
          if (res.data instanceof Blob) {
            testImg = window.URL.createObjectURL(res.data)
          } else {
            testImg = window.URL.createObjectURL(new Blob([res.data], {type: 'text/plain'}))
          }
          this.testImg = testImg
          this.$store.state.localPicture[this.imgUrl] = this.testImg
          // this.downloadDecodeFile(testImg)
          // this.localTest=testImg
          // this.blobToDataURL(res.data)
          this.scrollBottom()

        })
      }
    },
    downloadDecodeFile(file) {
      const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
      //blob:http://localhost:8080/b878edea-e649-4f8d-b723-c3f25454141b
      image.src = file;
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height);
        let imgUrl1 = canvas.toDataURL() //图片的base64地址
        this.localTest = imgUrl1
        localStorage.setItem(this.imgUrl, imgUrl1)
      }
    }
  }
}
</script>

<style scoped>
.avatar {
  background-color: gray;
  width: 40px;
  height: 40px;
  margin: 0 0 0 10px;
  /*圆角方形*/
  border-radius: 10px;
  /*圆形头像*/
  /*border-radius: 50%;*/
}

.avatar2 {
  background-color: gray;
  width: 60px;
  height: 60px;
  margin: 10px 0 0 10px;
  /*圆形头像*/
  border-radius: 50%;
}

.avatar3 {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

.message {
  width: 300px;
}
</style>
